﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;

namespace USREOUCheck.Classes
{
    class ServiceRequest
    {
        #region Members 
        
        private static SortedSet<JuridicalPerson> persons = new SortedSet<JuridicalPerson>();

        public static SortedSet<JuridicalPerson> Persons
        {
            get 
            {
                if (persons != null)
                    return persons;
                else
                    return null;
            }
        }

        #endregion

        #region Public Methods

        public static void LoadCodesFromFile(string fileName)
        {
            FileInfo file = new FileInfo(@fileName);
            
            if (!file.Exists)
                throw new FileNotFoundException("Файл: " + fileName + " не найден.");

            using (StreamReader sr = file.OpenText())
            {
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();

                    Persons.Add(new JuridicalPerson(line, false));
                }
            }
        }

        public static Stream SendRequest(string individualCode, bool isJuridical)
        {
            Uri url = new Uri("http://sta.gov.ua/control/uk/vat/search");
            HttpWebRequest dRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            dRequest.Method = "POST";
            dRequest.Timeout = dRequest.Timeout;
            dRequest.ContentType = "application/x-www-form-urlencoded";
            dRequest.UserAgent = "Mozilla/5.0";

            int i = isJuridical ? 1 : 0;

            byte[] sendData = Encoding.GetEncoding(65001).GetBytes("individualCode=" + individualCode + "&isJuridical=" + i);
            
            dRequest.ContentLength = sendData.Length;

            using (var stream = dRequest.GetRequestStream())
            {
                stream.Write(sendData, 0, sendData.Length);
            }

            return dRequest.GetResponse().GetResponseStream();
        }   

        public static string ParseRequestResult(Stream request)
        {

            StringBuilder result = new StringBuilder();

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(request, true);
            
            string xPath = "/html[1]/body[1]/table[1]/tr[1]/td[1]/table[1]/tr[3]/td[1]/table[1]/tr[1]/td[1]/table[1]/tr[1]/td[3]/table[3]";
            HtmlAgilityPack.HtmlNodeCollection cols = doc.DocumentNode.SelectNodes(xPath);

            foreach (HtmlAgilityPack.HtmlNode col in cols)
            {
                string withoutNewLine = col.InnerText.Replace("\n", "");
                string replacement = Regex.Replace(withoutNewLine, @"\u0020{2,}", "\u000A");               
                result.AppendLine(" |===================================================================");                
                result.AppendLine(replacement);                                
            }

            return result.ToString();
        }

        public static void DeleteFilesAndDirectory(string directory)
        {
            DirectoryInfo dir = new DirectoryInfo(directory);
            
            if (dir.Exists)
                dir.Delete(true);
        }

        #endregion Public Methods
    }
}
